package commodity

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/commodity"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
    commodityReq "github.com/flipped-aurora/gin-vue-admin/server/model/commodity/request"
)

type CommodityService struct {
}

// CreateCommodity 创建Commodity记录
// Author [piexlmax](https://github.com/piexlmax)
func (commodityService *CommodityService) CreateCommodity(commodity commodity.Commodity) (err error) {
	err = global.GVA_DB.Create(&commodity).Error
	return err
}

// DeleteCommodity 删除Commodity记录
// Author [piexlmax](https://github.com/piexlmax)
func (commodityService *CommodityService)DeleteCommodity(commodity commodity.Commodity) (err error) {
	err = global.GVA_DB.Delete(&commodity).Error
	return err
}

// DeleteCommodityByIds 批量删除Commodity记录
// Author [piexlmax](https://github.com/piexlmax)
func (commodityService *CommodityService)DeleteCommodityByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]commodity.Commodity{},"id in ?",ids.Ids).Error
	return err
}

// UpdateCommodity 更新Commodity记录
// Author [piexlmax](https://github.com/piexlmax)
func (commodityService *CommodityService)UpdateCommodity(commodity commodity.Commodity) (err error) {
	err = global.GVA_DB.Save(&commodity).Error
	return err
}

// GetCommodity 根据id获取Commodity记录
// Author [piexlmax](https://github.com/piexlmax)
func (commodityService *CommodityService)GetCommodity(id uint) (commodity commodity.Commodity, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&commodity).Error
	return
}

// GetCommodityInfoList 分页获取Commodity记录
// Author [piexlmax](https://github.com/piexlmax)
func (commodityService *CommodityService)GetCommodityInfoList(info commodityReq.CommoditySearch) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&commodity.Commodity{})
    var commoditys []commodity.Commodity
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.Commodity_user != nil {
        db = db.Where("commodity_user = ?",info.Commodity_user)
    }
    if info.Commodity_title != "" {
        db = db.Where("commodity_title LIKE ?","%"+ info.Commodity_title+"%")
    }
    if info.Commodity_send != nil {
        db = db.Where("commodity_send = ?",info.Commodity_send)
    }
    if info.Commodity_position != nil {
        db = db.Where("commodity_position = ?",info.Commodity_position)
    }
    if info.Commodity_label != nil {
        db = db.Where("commodity_label = ?",info.Commodity_label)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }
	err = db.Limit(limit).Offset(offset).Find(&commoditys).Error
	return  commoditys, total, err
}
